package com.changgou.order.controller;

import com.changgou.order.pojo.OrderItem;
import com.changgou.order.service.CartService;
import entity.Result;
import entity.StatusCode;
import entity.TokenDecode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Security;
import java.util.List;

/**
 * 购物车操作
 */
@RestController
@RequestMapping(value = "/cart")
public class CartController {

    @Autowired
    private TokenDecode tokenDecode;

    @Autowired
    private CartService cartService;
    /**
     *  加入购物车
     *  1.加入购物车数量
     *  2.商品id
     */
    @GetMapping(value = "/add")
    public Result add(Integer num,Long id){
        String username=tokenDecode.getUserInfo().get("username");
        cartService.add(num,id,username);
        return new Result(true, StatusCode.OK,"加入购物车成功");
    }

    //购物车列表
    @GetMapping(value = "/list")
    public Result<List<OrderItem>>list(){
        //用户的令牌信息->解析令牌信息->username
        //Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
        String token = details.getTokenValue();
        //String username="szitheima";
        String username=tokenDecode.getUserInfo().get("username");
        List<OrderItem> orderItems=cartService.list(username);
        return new Result<List<OrderItem>>(true,StatusCode.OK,"查询购物车列表成功",orderItems);
    }
}
